﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Q.Framework.WebControls;
using System.Web.UI.WebControls;
using Q.Framework.Utility;
using System.Web.UI;
using System.Web;

namespace Q.Framework.WebCode
{
    abstract public class LookupSearchControl : System.Web.UI.UserControl
    {
        abstract public void OnSelect();
        abstract public QTextBox GetKeyFieldControl();
        abstract public Label GetDescriptionFieldControl();
        abstract public ImageButton GetSearchButton();
        abstract public ImageButton GetOpenModalButton();
        abstract public ImageButton GetOpenCrudButton();
        abstract public AutoPageableGridView GetGridResult();
        abstract public QTextBox GetDescriptionFilterControl();
        abstract public AjaxControlToolkit.ModalPopupExtender GetCrudModal();
        abstract public AjaxControlToolkit.ModalPopupExtender GetSearchModal();
        abstract public System.Web.UI.HtmlControls.HtmlGenericControl GetCrudIframe();
        abstract public Button GetOkCrudButton();

        public ILookupSearch LookupDefinition
        {
            get { return ViewState["LookupDefinition_" + ID] as ILookupSearch; }
            set { ViewState["LookupDefinition_" + ID] = value; }
        }

        public Boolean IsValidValue
        {
            get { return Convert.ToBoolean(ViewState["LookupIsValidValue_" + ID] as String); }
            set { ViewState["LookupIsValidValue_" + ID] = value.ToString(); }
        }

        private Object selectedValue;
        public Object SelectedValue
        {
            get { return selectedValue; }
            set
            {
                selectedValue = value;
                if (ExternChange)
                {
                    GetKeyFieldControl().SetValue(GetKeyValueFromObject(value));
                    KeyFieldControl_TextChanged(GetKeyFieldControl(), null);
                }
            }
        }

        private Object GetKeyValueFromObject(Object obj)
        {
            if (obj == null)
                return String.Empty;

            return LookupDefinition.BusinessType.GetProperty(LookupDefinition.KeyFieldName).GetValue(obj, null);
        }

        private String GetDescriptionValueFromObject(Object obj)
        {
            if (obj == null)
                return String.Empty;

            return LookupDefinition.BusinessType.GetProperty(LookupDefinition.DescriptionFieldName).GetValue(obj, null) as String;
        }

        private Boolean ExternChange = true;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            GetKeyFieldControl().ValueType = LookupDefinition.TypeOfKeyTextBox;
            GetKeyFieldControl().TextChanged += new EventHandler(KeyFieldControl_TextChanged);
            GetOpenModalButton().Click += new ImageClickEventHandler(OpenModalButton_Click);
            GetGridResult().Bind += new BindHandle(GridResult_Bind);
            GetSearchButton().Click += new ImageClickEventHandler(OpenModalButton_Click);
            GetOpenCrudButton().Click += new ImageClickEventHandler(OpenCrudButton_Click);
            GetOkCrudButton().Click += new EventHandler(OkCrudButton_Click);
            GetGridResult().SelectedIndexChanged += new EventHandler(GridResult_SelectedIndexChanged);
            GetGridResult().DataKeyNames = new string[] { LookupDefinition.KeyFieldName };
            (GetGridResult().Columns[0] as BoundField).DataField = LookupDefinition.KeyFieldName;
            (GetGridResult().Columns[0] as BoundField).HeaderText = LookupDefinition.KeyFieldName;
            (GetGridResult().Columns[1] as BoundField).DataField = LookupDefinition.DescriptionFieldName;
            (GetGridResult().Columns[1] as BoundField).DataField = LookupDefinition.DescriptionFieldName;

        }

        public void GridResult_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetKeyFieldControl().SetValue(GetGridResult().SelectedDataKey[LookupDefinition.KeyFieldName]);
            KeyFieldControl_TextChanged(null, null);
        }

        protected void OkCrudButton_Click(object sender, EventArgs e)
        {
            KeyFieldControl_TextChanged(null, null);
        }

        protected void OpenCrudButton_Click(object sender, ImageClickEventArgs e)
        {
            LookupDefinition.CrudParameters.Add("ClientOkButtonID", GetOkCrudButton().ClientID);
            LookupDefinition.CrudParameters.Add("FastCrud", "S");
            LookupDefinition.CrudParameters.Add("ClientKeyFieldID", GetKeyFieldControl().ClientID);
            LookupDefinition.CrudParameters.Add("KeyFieldFastCrud", LookupDefinition.KeyFieldName);

            GetCrudIframe().Attributes["src"] = VirtualPathUtility.ToAbsolute(LookupDefinition.CrudUrl) + "?" + String.Join("&", LookupDefinition.CrudParameters.Select(p => p.Key + "=" + p.Value));

            GetCrudModal().Show();
        }

        protected void GridResult_Bind(int pageIndex, int PageSize)
        {
            var result = LookupDefinition.GetPagedList(GetDescriptionFilterControl().Text, pageIndex, PageSize);
            GetGridResult().VirtualItemCount = result.TotalCount;
            GetGridResult().DataSource = result;
            GetGridResult().DataBind();
        }

        protected void OpenModalButton_Click(object sender, ImageClickEventArgs e)
        {
            GetGridResult().BindGrid();
            GetSearchModal().Show();
        }

        protected void KeyFieldControl_TextChanged(object sender, EventArgs e)
        {
            ExternChange = false;

            String value = GetKeyFieldControl().Text;
            if (String.IsNullOrWhiteSpace(value))
            {
                IsValidValue = false;
                GetDescriptionFieldControl().Text = String.Empty;
                SelectedValue = null;
            }
            else
            {
                SelectedValue = LookupDefinition.GetObjectByKeyField(value);
                if (SelectedValue == null)
                {
                    IsValidValue = false;
                    GetDescriptionFieldControl().Text = "Registro Não Encontrado";
                    GetKeyFieldControl().Text = String.Empty;
                }
                else
                {
                    GetDescriptionFieldControl().Text = GetDescriptionValueFromObject(SelectedValue);
                }
            }

            OnSelect();
        }

        public void Clear()
        {

        }

        public T Get<T>()
        {
            if (IsValidValue)
                return (T)(SelectedValue = SelectedValue ?? LookupDefinition.GetObjectByKeyField(GetKeyFieldControl().Text));
            else
                return default(T);
        }

        public void Fill<T>(LookupSearch<T> definition)
        {
            LookupDefinition = definition;
        }
    }
}
